import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../views/Layout.vue'
import Login from '../views/Login.vue'
// import {asyncRouter} from './asyncRouter'
// import store from '../store'
//防止多次点击报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)



const createRouter = () => new VueRouter({
  mode: 'hash',
  routes: [{
    path: '/',
    redirect: '/login',
  },
  //登陆页
  {
    path: '/login',
    neme: 'login',
    component: Login,
  },
  {
    path: '*',
    name: '404',
    component: () => import('../views/exception/404.vue'),
  },
  {
    path: '/403',
    name: '403',
    component: () => import('../views/exception/403.vue'),
  },
  {
    path: '/500',
    name: '500',
    component: () => import('../views/exception/500.vue'),
  },
  //设置页面添加
  {
    path: '',
    component: Layout,
    redirect: '/set-views',
    children: [
      {
        path: '/set-views',
        name: '页面设置',
        component: () => import('@/views/setViews/SetViews.vue'),
      },
    ],
  },
  ]
})
const router = createRouter()


export function resetRouter() {
  // console.log('调用了清除路由');
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // the relevant part
}
export function filtrationRouter(routers) {
  let newRouter = []          // 遍历后台传来的路由字符串，转换为组件对象
  routers.forEach((item, i) => {
    if (item.permissionPath === 'Layout') {
      item.permissionPath = Layout
    }
    // console.log(item.path);
    newRouter.push({
      path: item.permissionUrl,
      component: item.permissionPath,
      title: item.permissionName,
      redirect: item.permissionRedirect,
      icon: item.icon,
      children: []
    })

    if (item.children && item.children.length >= 1) {
      item.children.forEach((v) => {
        newRouter[i].children.push({
          path: v.permissionUrl,
          component: _import(v.permissionPath),
          title: v.permissionName,
          redirect: v.permissionRedirect,
          children: []
        })
        if (v.children && v.children.length >= 1) {
          let len = newRouter[i].children.length;
          let children = [...v.children];
          children.forEach((v1) => {
            newRouter[i].children[len - 1].children.push({
              path: v1.permissionUrl,
              component: _import(v.permissionPath),
              title: v1.permissionName,
            });
          });
        }
      })
    }
  })
  return newRouter
}

function _import(file) {
  return (resolve) => require([`@/views${file}.vue`], resolve)
}
export default router
